<template>
  <div class="app-container">
    <!--表头工具栏-->
    <div class="handle-box">
      <el-row>
        <span class="span_label">{{ $t("operating.searchDate") }}</span>
        <el-date-picker
          v-model="dateValue"
          type="daterange"
          :range-separator="$t('operating.line')"
          :start-placeholde="$t('operating.StartTime')"
          :end-placeholde="$t('operating.EndTime')"
          :clearable="false"
          value-format="yyyy-MM-dd"
          size="mini"
          :picker-options="this.v_DateTimePickerOptions"
          style="width: 240px"
          @change="timeChange"
        />

        <!-- <span>{{$t('inspection.inspection')}}</span> -->

        <!-- <span>考勤名称</span> -->

        <!--可支持搜索-->
        <span class="span_label">类型</span>
        <el-select
          v-model="searchTaskValue"
          filterable
          :placeholder="$t('operating.pleaseChosen')"
          style="width: 120px"
          size="mini"
        >
          <el-option
            v-for="item in this.searchTasks"
            :key="item.idx"
            :label="item.pollingName"
            :value="item.idx"
          />
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          style="margin-left: 10px"
          @click="searchData"
        >{{ $t("operating.search") }}</el-button>

        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="leadingOutData"
        >{{ $t("operating.export") }}</el-button>
      </el-row>
    </div>

    <el-tabs v-model="searchType" @tab-click="handleClick">
      <el-tab-pane
        :label="$t('inspection.inspection')"
        :name="$t('inspection.inspection')"
      >
        <div>
          <!--表格-->
          <el-table
            class="datalist"
            :data="tableData1"
            :height="tableMaxHeight"
            :row-class-name="tableRowClassName1"
          >
            <!-- 展开框 -->
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-card class="detail-card">
                  <p class="detail-content">{{ props.row.detail }}</p>
                </el-card>
              </template>
            </el-table-column>

            <el-table-column
              prop="pollingName"
              :label="$t('inspection.pollingName')"
              min-width="150"
            />
            <el-table-column
              prop="timeStart"
              :label="$t('operating.StartTime')"
              min-width="200"
            />
            <el-table-column
              prop="timeEnd"
              :label="$t('operating.EndTime')"
              min-width="200"
            />
            <!--<el-table-column prop="inspectiondetail" label="巡检详情" width="250"></el-table-column>-->
            <el-table-column
              prop="result"
              :label="$t('inspection.result')"
              min-width="150"
            />
            <el-table-column
              prop="descResult"
              :label="$t('inspection.descResult')"
              min-width="300"
            />

            <!--操作-->
            <el-table-column :label="$t('operating.operating')">
              <template slot-scope="scope">
                <el-tooltip
                  :content="$t('inspection.MonitoringSnapshot')"
                  placement="top"
                >
                  <el-button
                    class="table-scope-button"
                    size="mini"
                    type="text"
                    icon="al-icon-carzhaopian-copy"
                    :disabled="
                      scope.row.snapUrlList === undefined ? true : false
                    "
                    @click="handleLook(scope.$index, scope.row)"
                  />
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              background
              :page-sizes="[10, 20, 30, 50, 70, 100]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="this.tableDataNum1"
              @size-change="handleSizeChange1"
              @current-change="handleCurrentChange1"
            />
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane
        :label="$t('inspection.peopleData')"
        :name="$t('inspection.peopleData')"
      >
        <div>
          <el-table
            class="datalist"
            :data="tableData2"
            :height="tableMaxHeight"
            :row-class-name="tableRowClassName2"
          >
            <!-- 展开框 -->
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-card class="detail-card">
                  <p class="detail-content">{{ props.row.detail }}</p>
                </el-card>
              </template>
            </el-table-column>

            <el-table-column
              prop="resourceName"
              :label="$t('inspection.pollingPeopleName')"
              min-width="150"
            />
            <el-table-column
              prop="pollingName"
              :label="$t('inspection.pollingName')"
              min-width="150"
            />
            <el-table-column
              prop="timeStart"
              :label="$t('operating.StartTime')"
              min-width="200"
            />
            <el-table-column
              prop="timeEnd"
              :label="$t('operating.EndTime')"
              min-width="200"
            />
            <!--<el-table-column prop="inspectiondetail" label="巡检详情" width="250"></el-table-column>-->
            <el-table-column
              prop="result"
              :label="$t('inspection.result')"
              min-width="150"
            />
            <el-table-column
              prop="descResult"
              :label="$t('inspection.descResult')"
              min-width="300"
            />

            <!--操作-->
            <el-table-column :label="$t('operating.operating')">
              <template slot-scope="scope">
                <el-tooltip
                  :content="$t('inspection.MonitoringSnapshot')"
                  placement="top"
                >
                  <el-button
                    class="table-scope-button"
                    size="mini"
                    type="text"
                    icon="al-icon-carzhaopian-copy"
                    :disabled="
                      scope.row.snapUrlList === undefined ? true : false
                    "
                    @click="handleLook(scope.$index, scope.row)"
                  />
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              background
              :page-sizes="[10, 20, 30, 50, 70, 100]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="this.tableDataNum2"
              @size-change="handleSizeChange2"
              @current-change="handleCurrentChange2"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 照片查看器 -->
    <el-dialog
      :visible.sync="dialogVisible"
      width="50%"
      style="text-align: center"
      :close-on-click-modal="false"
    >
      <el-carousel height="450px" :loop="true" :autoplay="false">
        <el-carousel-item v-for="(item, index) in photoPaths" :key="index">
          <h3 style="margin-bottom: 20px">{{ item.name }}</h3>
          <img :src="item.path" style="height: 400px">
        </el-carousel-item>
      </el-carousel>
    </el-dialog>
  </div>
</template>

<script>
import { baseUrl } from '@/utils/global'
import Cookie from 'js-cookie'
import { Encrypt, Decrypt } from '@/common/secret.js'
import {
  getList,
  getInspectionPeopleList,
  getInspectionList,
  getPeopleList,
  downloadFile
} from '@/api/cy.js'
var dayjs = require('dayjs')
export default {
  data() {
    return {
      activeName: '巡检任务',
      tableShow: true,
      searchType: '巡检任务', // 查询类型
      searchTaskValue: -1, // 搜索区域
      searchTasks: [],

      dateValue: [], // 查询的日期范围
      startDate: '',
      endDate: '',
      tableData1: [], // 表格数据
      tableData2: [], // 表格数据
      tableDataNum1: 0, // 搜索到的数据总数
      tableDataNum2: 0, // 搜索到的数据总数
      cur_page1: 1, // 表格当前页码
      cur_page2: 1, // 表格当前页码
      size_page1: 10,
      size_page2: 10,
      inspeDetail: '', // 巡检详情内容

      dialogVisible: false, // 图片快照dialog
      photoPaths: [],
      tableMaxHeight: window.innerHeight - 240
    }
  },
  mounted() {
    this.setQueryTime()

    this.windowRefresh()
    const self = this
    window.onresize = function temp() {
      self.windowRefresh()
    }

    this.init()
  },
  methods: {
    handleClick(tab, event) {
      // 设置选择默认值
      this.searchTaskValue = -1
      // 切换下拉框中的数据
      // 切换表格
      if (
        this.searchType === '巡检任务' ||
        this.searchType === 'Inspection Tasks' ||
        this.searchType === '巡檢任務'
      ) {
        this.tableShow = true
        this.getInspectionList()
      } else if (
        this.searchType === '巡检人员' ||
        this.searchType === 'Inspector' ||
        this.searchType === '巡检人员'
      ) {
        this.tableShow = false
        this.getInspectionPeopleList()
      }
    },

    timeChange(value) {
      console.log(this.dateValue)
    },

    /**
     * 查看巡检点摄像头拍摄的照片
     */
    handleLook(index, row) {
      this.dialogVisible = true
      this.photoPaths = []
      if (typeof row.snapUrlList !== 'undefined') {
        const json = $.parseJSON(row.snapUrlList)
        console.log(json)
        let name
        let path
        for (let i = 0; i < json.length; i++) {
          name = json[i].fenceName + '   ' + json[i].snapTime
          path = baseUrl + json[i].snapUrl
          const obj = { name: name, path: path }
          this.photoPaths.push(obj)
        }
      } else {
        this.v_MyMessage(this.$t('Notice.noInspectionPictures'), 'warning')
      }
    },

    /**
     * 设置查询时间
     */
    setQueryTime() {
      const myDate = new Date()
      const year = myDate.getFullYear()
      const month = myDate.getMonth()
      const day = myDate.getDate()
      const dateStart = dayjs(new Date(year, month, day, '08', '00', '00').getTime()).format('YYYY-MM-DD HH:mm:ss')
      const dateEnd = dayjs(new Date(year, month, day, '18', '00', '00').getTime()).format('YYYY-MM-DD HH:mm:ss')
      this.dateValue = [
        dateStart,
        dateEnd
      ]
    },

    /*
     * 查看巡检详情
     * */
    checkDetail(index, row) {
      console.log(index, row)
      const item = this.tableData1[index]
      this.inspeDetail = item.inspectiondetail
    },

    tableRowClassName1(row, rowIndex) {
      if (row.row.result === '任务未完成') {
        return 'background-red'
      } else if (row.row.result === '任务完成') {
        return 'background-green'
      }
    },

    tableRowClassName2(row, rowIndex) {
      if (row.row.result === '任务未完成') {
        return 'background-red'
      } else if (row.row.result === '任务完成') {
        return 'background-green'
      }
    },

    /*
     * 根据条件搜索数据
     * */
    searchData() {
      this.getData()
    },
    formatDate(time) {
      // time = time * 1000
      const date = new Date(time)
      console.log(new Date(time))
      return this.DateFormatDate(date, 'yyyy-MM-dd')
    },
    DateFormatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
      }
      const o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      }
      for (const k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          const str = o[k] + ''
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1 ? str : this.padLeftZero(str)
          )
        }
      }
      return fmt
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length)
    },

    formatGet(str) {
      str = str.replace(/\+/g, '%2B')
      str = str.replace(/\&/g, '%26')
      str = str.replace(/\=/g, '%3D')
      const strdata = str
      return strdata
    },

    /*
     * 导出数据到表格
     * */
    leadingOutData() {
      this.startDate = this.dateValue[0]
      this.endDate = this.dateValue[1]
      const aa1 = 'timeStart=' + this.startDate
      const bb1 = 'timeEnd=' + this.endDate
      const cc1 = 'token=' + Cookie.get('token')
      const strTime = Encrypt(aa1)
      const endTime = Encrypt(bb1)
      const ecpToken = Encrypt(cc1)
      const a1 = this.formatGet(strTime)
      const b1 = this.formatGet(endTime)
      const c1 = this.formatGet(ecpToken)
      // let strTime=Encrypt(this.startDate);
      // let endTime=Encrypt(this.endDate);
      // let ecpToken=Encrypt(Cookie.get("token"))

      if (this.tableShow) {
        const urlPath =
          '/report/reportPolling?' +
          a1 +
          '&' +
          b1 +
          '&' +
          c1

        // let urlPath =
        // "/report/reportPolling?" +
        // (this.searchTaskValue == -1
        //   ? ""
        //   : "pollingId=" + this.searchTaskValue) +
        // "&timeStart=" +
        // strTime +
        // "&timeEnd=" +
        // endTime +
        // "&token=" +
        // ecpToken;

        // let urlPath =
        //   "/report/reportPolling?" +
        //   (this.searchTaskValue == -1
        //     ? ""
        //     : "pollingId=" + this.searchTaskValue) +
        //   "&timeStart=" +
        //   this.startDate +
        //   "&timeEnd=" +
        //   this.endDate +
        //   "&token=" +
        //   Cookie.get("token");
        const filename = 'inspect_' + new Date().getTime() + '.xls'
        downloadFile(urlPath, filename)
      } else {
        // window.location.href =
        //   baseUrl +
        //   "/report/reportReportPollingPersonal?" +
        //   (this.searchTaskValue == -1
        //     ? ""
        //     : "pollingId=" + this.searchTaskValue) +
        //   "&timeStart=" +
        //   this.startDate +
        //   "&timeEnd=" +
        //   this.endDate +
        //   "&token=" +
        //   Cookie.get("token");
        const urlPath =
          '/report/reportReportPollingPersonal?' +
          (this.searchTaskValue == -1
            ? ''
            : 'pollingId=' + this.searchTaskValue) +
          '&timeStart=' +
          this.startDate +
          '&timeEnd=' +
          this.endDate +
          '&token=' +
          Cookie.get('token')
        const filename = 'personal_' + new Date().getTime() + '.xls'
        downloadFile(urlPath, filename)
      }
    },
    /*
     * 分页导航
     * */
    handleCurrentChange1(val) {
      this.cur_page1 = val
      this.getData()
    },

    handleSizeChange1(val) {
      this.size_page1 = val
      this.getData()
    },

    handleCurrentChange2(val) {
      this.cur_page2 = val
      this.getData()
    },

    handleSizeChange2(val) {
      this.size_page2 = val
      this.getData()
    },

    getData() {
      this.startDate = this.dateValue[0]
      this.endDate = this.dateValue[1]
      // 查询的是单个人员的信息
      var start_date = this.formatDate(this.startDate)
      var end_date = this.formatDate(this.endDate)

      const param = {
        pageNum: this.tableShow === true ? this.cur_page1 : this.cur_page2,
        pageSize: this.tableShow === true ? this.size_page1 : this.size_page2,
        param: {
          timeStart: start_date,
          timeEnd: end_date
        }
      }

      if (this.tableShow) {
        // 按照巡检任务查询
        if (this.searchTaskValue != -1) {
          param.param['pollingId'] = this.searchTaskValue
        }
        this.tableData1 = []
        getList(param).then((res) => {
          const RES = this.responseUse(res)
          if (RES.content.length > 0) {
            this.tableDataNum1 = RES.totalSize // 得知数据总数，用于显示表格底部数据总数
            this.tableData1 = RES.content
          } else {
            this.v_MyMessage(this.$t('Notice.noDataHasBeenFound'), 'warning')
          }
        })
      } else {
        // 按照巡检人员查询
        if (this.searchTaskValue != -1) {
          param.param['resourceId'] = this.searchTaskValue
        }

        this.tableData2 = []

        getPeopleList(param).then((res) => {
          const RES = this.responseUse(res)
          if (RES.content.length > 0) {
            this.tableDataNum2 = RES.totalSize // 得知数据总数，用于显示表格底部数据总数
            this.tableData2 = RES.content
          } else {
            this.v_MyMessage(this.$t('Notice.noDataHasBeenFound'), 'warning')
          }
        })
      }
    },

    // 获取巡检任务列表
    getInspectionList() {
      getInspectionList().then((res) => {
        const RES = this.responseUse(res)
        const tempJson = {
          pollingName: this.$t('alarm.alarmTypes.all'),
          idx: -1
        }
        RES.splice(0, 0, tempJson)
        // this.tableData1=res.data;
        this.searchTasks = RES
      })
    },

    // 获取巡检人员列表
    getInspectionPeopleList() {
      getInspectionPeopleList().then((res) => {
        const RES = this.responseUse(res)
        // 添加“全部”
        for (let i = 0; i < RES.length; i++) {
          RES[i]['pollingName'] = RES[i].name
          RES[i].idx = RES[i].resourceId
        }
        RES.splice(0, 0, {
          pollingName: this.$t('alarm.alarmTypes.all'),
          idx: -1
        })
        this.searchTasks = RES
        this.searchData()
      })
    },

    init() {
      this.getInspectionList()

      // 加载全部巡检结果
      this.getData()
    },
    // 刷新窗口
    windowRefresh: function() {
      this.tableMaxHeight = window.innerHeight - 240
    }
  }
}
</script>

<style scoped>
.handle-box {
  min-width: 1000px;
}
.detail-card {
  width: 500px;
}

.detail-content {
  white-space: pre-line;
  font-size: 14px;
  line-height: 25px;
  color: #f1a11e;
}

.span_label {
  margin-right: 8px;
  margin-left: 8px;
}
.handle-box {
  margin-bottom: 10px;
}
</style>
